import modelExtend from 'dva-model-extend';
import { message } from 'antd';
import { query, detail, control, update, create, deleteDevice, defaultData, operatorList, runningRecordList } from '../services/device';
import { pageModel } from './common';
import { isSuccess } from '../configs/error';
import { fetchHelper } from '../utils/util';
import validateFun from '../utils/regExp';

const validate = {
	name: validateFun('name'),
	mac: validateFun('mac')
};

export default modelExtend(pageModel, {
	namespace: 'device',

	state: {
		creating: false,
		tempDetail: {},
		tableDisplay: [],
		detailData: {}
	},

	subscriptions: {
		setup({ dispatch, history }) {
			history.listen(location => {
				if (location.pathname === '/deviceList') { // 每次刷新一下，获取最新
					// dispatch({
					//   type: 'productList/query'
					// });
				}
			});
		},
	},

	effects: {

		*query({ payload }, { call, put }) {
			if (JSON.stringify(payload) === '{}') {
				payload = { ...defaultData };
			}
			const data = yield call(query, payload);
			if (isSuccess(data)) {
				const { data: resultData, display } = data;
				const startIndex = (Number(resultData.current) - 1) * Number(resultData.size);
				resultData.records.forEach((item, index) => {
					item.index = startIndex + index + 1;
				});
				yield put({
					type: 'querySuccess',
					payload: {
						list: resultData.records,
						pagination: {
							current: Number(resultData.current) || 1,
							pageSize: Number(resultData.size) || 10,
							total: resultData.total,
						},
						tableDisplay: display
					},
				});
			}
		},
		*createDevice({ payload }, { call, put }) {
			if (fetchHelper.fetching('createDevice')) return;
			const res = yield call(create, payload);
			fetchHelper.unfetching('createDevice');
			if (isSuccess(res)) {
				message.success('添加成功');
				yield put({
					type: 'set',
					payload: {
						isShowAdd: false
					}
				});
				yield put({ type: 'query', payload: {} });
			}
		},
		*update({ payload }, { call }) {
			const res = yield call(update, payload);
			if (isSuccess(res)) {
				message.success('更新成功');
				return;
			} else {
				message.error(res.message);
			}
		},
		*delete({ payload }, { select, call, put }) {
			const list = yield select(state => state.device.list);
			const pagination = yield select(state => state.device.pagination);
			// yield put({ type: 'remove', ids: payload });
			const res = yield call(deleteDevice, payload);
			const hasSuccess = res.data && res.data.includes('成功');
			if (isSuccess(res)) {
				message[hasSuccess ? 'success' : 'error'](res.data);
				// if (hasSuccess) {
				// 	yield put({
				// 		type: 'query',
				// 		payload: {},
				// 	});
				// 	yield put({
				// 		type: 'updateState',
				// 		payload: {
				// 			selectedRowKeys: [],
				// 		},
				// 	});
				// }
			} else {
				yield put({ type: 'list', list });
			}
			yield put({
				type: 'query',
				payload: {
					current: pagination.current,
					size: pagination.pageSize,
				},
			});
			yield put({
				type: 'updateState',
				payload: {
					selectedRowKeys: [],
				},
			});
		},
		*detail({ payload }, { call, put }) {
			yield put({
				type: 'set',
				payload: { tempDetail: {} }
			});
			const data = yield call(detail, payload);
			if (data.code === '200') {
				const resultData = data.data;
				const { mac, name } = resultData;
				yield put({
					type: 'actionSuccess',
					payload: {
						detailData: resultData,
						tempDetail: { mac, name }
					}
				});
			} else {
				yield put({
					type: 'actionSuccess',
					payload: {
						detailData: {}
					}
				});
				throw data;
			}
		},
		*queryOperator({ payload }, { call, put }) {
			if (JSON.stringify(payload) === '{}') {
				payload = { defaultData };
			}
			const data = yield call(operatorList, payload);
			if (data) {
				const resultData = data.data;
				const startIndex = (resultData.current - 1) * resultData.size;
				resultData.records.forEach((item, index) => {
					item.index = startIndex + index + 1;
				});
				yield put({
					type: 'actionSuccess',
					payload: {
						operatorList: resultData.records,
						operatorPagination: {
							current: Number(payload.page) || 1,
							pageSize: Number(resultData.size) || 10,
							total: resultData.total,
						}
					},
				});
			}
		},
		*queryRunningRecord({ payload }, { call, put }) {
			if (JSON.stringify(payload) === '{}') {
				payload = { defaultData };
			}
			const data = yield call(runningRecordList, payload);
			if (data) {
				const resultData = data.data;
				const startIndex = (resultData.current - 1) * resultData.size;
				resultData.records.forEach((item, index) => {
					item.index = startIndex + index + 1;
				});
				yield put({
					type: 'actionSuccess',
					payload: {
						runningRecordList: resultData.records,
						runningRecordPagination: {
							current: Number(payload.current) || 1,
							pageSize: Number(payload.size) || 10,
							total: resultData.total,
						}
					},
				});
			}
		},
		*control({ payload }, { call }) {
			const data = yield call(control, payload);
			if (isSuccess(data)) {
				message.success('控制成功！', 2);
			}
		}
	},

	reducers: {

		actionSuccess(state, { payload }) {
			return { ...state, ...payload };
		},

		showModal(state, { payload }) {
			return { ...state, ...payload, modalVisible: true };
		},

		hideModal(state) {
			return { ...state, modalVisible: false };
		},

		switchIsMotion(state) {
			return { ...state, isMotion: !state.isMotion };
		},
		set(state, { payload }) {
			return { ...state, ...payload };
		},

		setData(state, { payload }) {
			const { error, ...temp } = { ...state.tempDetail, ...payload };
			const newError = {};
			Object.keys(temp).forEach(key => {
				newError[key] = validate[key] ? validate[key](temp[key]) : null;
			});
			return {
				...state,
				tempDetail: { ...temp, error: newError }
			};
		},
		updateData(state, { payload }) {
			return {
				...state,
				tempDetail: { ...state.tempDetail, ...payload }
			};
		},
		remove(state, { id, ids }) {
			const list = ids
				? state.list.filter(t => !ids.includes(t.sno))
				: state.list.filter(t => t.sno !== id);
			return { ...state, list };
		},
	},
});
